/**
 * Notes: 管理员模块业务逻辑 - 宠物门店预约小程序
 * Date: 2025-01-27 
 */

const BaseService = require('./base_service.js');
const AppointmentModel = require('../model/appointment_model.js');
const UserModel = require('../model/user_model.js');
const PetModel = require('../model/pet_model.js');
const StoreModel = require('../model/store_model.js');
const timeUtil = require('../../framework/utils/time_util.js');

class AdminService extends BaseService {

	/**
	 * 获取本店预约列表
	 * @param {string} adminId 管理员ID
	 * @param {string} date 日期筛选
	 * @param {number} status 状态筛选
	 * @param {number} page 页码
	 * @param {number} size 每页数量
	 * @returns {Object} 预约列表
	 */
	async getStoreAppointments(adminId, date = null, status = null, page = 1, size = 20) {
		// 获取管理员信息，确定管理的门店
		const admin = await this.getAdminInfo(adminId);
		if (!admin) {
			throw new Error('管理员不存在');
		}

		const storeId = admin.storeId;
		if (!storeId) {
			throw new Error('管理员未分配门店');
		}

		// 构建查询条件
		let where = { storeId: storeId };

		// 按日期筛选
		if (date) {
			const dateRange = this.getDateRange(date);
			where.appointmentTime = {
				$gte: dateRange.start,
				$lte: dateRange.end
			};
		}

		// 按状态筛选
		if (status !== null) {
			where.status = status;
		}

		let fields = '_id,appointmentNumber,userId,petIds,serviceId,employeeId,deviceId,appointmentTime,appointmentEndTime,status,totalAmount,payAmount,payTime,createTime';
		let orderBy = { appointmentTime: -1 };

		const result = await AppointmentModel.getList(where, fields, orderBy, page, size, true, 0);
		
		// 补充关联信息
		const appointments = await this.enrichAdminAppointmentList(result.list);
		
		return {
			list: appointments,
			total: result.total,
			page: page,
			size: size,
			storeInfo: {
				storeId: storeId,
				storeName: admin.storeName
			}
		};
	}

	/**
	 * 更新预约单状态
	 * @param {string} adminId 管理员ID
	 * @param {string} appointmentId 预约ID
	 * @param {number} status 新状态
	 * @returns {Object} 更新结果
	 */
	async updateAppointmentStatus(adminId, appointmentId, status) {
		// 获取管理员信息
		const admin = await this.getAdminInfo(adminId);
		if (!admin) {
			throw new Error('管理员不存在');
		}

		// 获取预约信息
		const appointment = await AppointmentModel.getOne({ _id: appointmentId });
		if (!appointment) {
			throw new Error('预约单不存在');
		}

		// 检查权限：管理员只能操作自己门店的预约
		if (appointment.storeId !== admin.storeId) {
			throw new Error('无权限操作该预约单');
		}

		// 验证状态转换
		if (!this.isValidStatusTransition(appointment.status, status)) {
			throw new Error('状态转换不合法');
		}

		// 更新状态
		await AppointmentModel.edit({ _id: appointmentId }, {
			status: status,
			updateTime: timeUtil.time()
		});

		// 返回更新后的预约信息
		return await this.enrichAdminAppointmentDetail(appointment);
	}

	/**
	 * 获取管理员信息
	 * @param {string} adminId 管理员ID
	 * @returns {Object} 管理员信息
	 */
	async getAdminInfo(adminId) {
		// 这里应该从admins表获取管理员信息
		// 暂时模拟管理员信息
		return {
			_id: adminId,
			username: 'admin',
			role: 'store_manager',
			storeId: 'store_001',
			storeName: '宠物美容店'
		};
	}

	/**
	 * 丰富管理员预约列表信息
	 * @param {Array} appointments 预约列表
	 * @returns {Array} 丰富后的预约列表
	 */
	async enrichAdminAppointmentList(appointments) {
		const enrichedAppointments = [];
		
		for (let appointment of appointments) {
			try {
				const enriched = await this.enrichAdminAppointmentDetail(appointment);
				enrichedAppointments.push(enriched);
			} catch (error) {
				console.error('丰富预约信息失败:', error);
				enrichedAppointments.push(appointment);
			}
		}
		
		return enrichedAppointments;
	}

	/**
	 * 丰富管理员预约详情信息
	 * @param {Object} appointment 预约信息
	 * @returns {Object} 丰富后的预约信息
	 */
	async enrichAdminAppointmentDetail(appointment) {
		// 获取用户信息
		const user = await UserModel.getOne({ _id: appointment.userId }, 'nickName,avatarUrl,phone');
		
		// 获取宠物信息
		const pets = [];
		for (let petId of appointment.petIds) {
			const pet = await PetModel.getOne({ _id: petId }, 'name,species,avatar');
			if (pet) {
				pets.push(pet);
			}
		}

		// 获取门店信息
		const store = await StoreModel.getOne({ _id: appointment.storeId }, 'name,address,phone');

		return {
			...appointment,
			userInfo: user,
			petInfo: pets,
			storeInfo: store
		};
	}

	/**
	 * 验证状态转换是否合法
	 * @param {number} fromStatus 原状态
	 * @param {number} toStatus 目标状态
	 * @returns {boolean} 是否合法
	 */
	isValidStatusTransition(fromStatus, toStatus) {
		const validTransitions = {
			[AppointmentModel.STATUS.PENDING_PAY]: [AppointmentModel.STATUS.CANCELLED],
			[AppointmentModel.STATUS.PAID]: [AppointmentModel.STATUS.IN_SERVICE, AppointmentModel.STATUS.CANCELLED],
			[AppointmentModel.STATUS.IN_SERVICE]: [AppointmentModel.STATUS.COMPLETED],
			[AppointmentModel.STATUS.COMPLETED]: [],
			[AppointmentModel.STATUS.CANCELLED]: []
		};

		return validTransitions[fromStatus] && validTransitions[fromStatus].includes(toStatus);
	}

	/**
	 * 获取日期范围
	 * @param {string} date 日期字符串 (YYYY-MM-DD)
	 * @returns {Object} 开始和结束时间戳
	 */
	getDateRange(date) {
		const targetDate = new Date(date);
		const start = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate());
		const end = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate() + 1);
		
		return {
			start: Math.floor(start.getTime() / 1000),
			end: Math.floor(end.getTime() / 1000) - 1
		};
	}
}

module.exports = AdminService;
